<?php
class url_settingModel extends baseModel{
    protected $table = 'url_setting';

    //规则列表
    public function url_list() {
        return $this->select('','','sequence asc,id asc');
    }

    //规则信息
    public function info($id) {
        return $this->find('id='.$id);
    }

    //添加规则
    public function add($data)
    {
        $data['url']=html_in($data['url']);
        $data['rule']=html_in($data['rule']);
        return $this->insert($data);
    }
    //编辑规则
    public function edit($data)
    {
        $condition['id']=intval($data['id']);
        $data['url']=html_in($data['url']);
        $data['rule']=html_in($data['rule']);
        return $this->update($condition,$data); 
    }
    //删除规则
    public function del($id)
    {
        return $this->delete('id='.intval($id)); 
    }

    //保存配置
    public function save_config(){
        $config=require(BASE_PATH.'/config.php');
        $list=$this->url_list();
        if(empty($list)){
            return;
        }
        $REWRITE=array();
        foreach ($list as $value) {
            //普通规则
            $rule=html_out($value['rule']);
            $url=html_out($value['url']);
            //分页规则
            $rule_array=explode('.', $rule);
            if(substr($rule, 0,-1)=='/'){
                $REWRITE["config['REWRITE']['" . substr($rule, 0,-1).'-page-<page>/'. "']"]=$url;

            }else if(count($rule_array)>1){
                $ext=end($rule_array);
                $page_rule=substr($rule,0,-strlen($ext)-1);
                $REWRITE["config['REWRITE']['" . $page_rule.'-page-<page>.'.$ext. "']"]=$url;
            }else{
                $REWRITE["config['REWRITE']['" . $rule.'-page-<page>'. "']"]=$url;
            }
            $REWRITE["config['REWRITE']['" . $rule. "']"]=$url;
            
        }
        return $this->save_file(ROOT_PATH.'inc/base/rewrite.ini.php',$REWRITE);
    }

    //保存配置
    public function save_file($config_file,$array) {
        if (empty($array) || !is_array($array)) {
            return false;
        }
        $config = ''; //读取配置
        foreach ($array as $name => $value) {
            $value = "'" . $value . "'"; 
            $config .= '$'.$name." = ".$value .";\n";
        }
        // 写入配置
        $config="<?php \n//伪静态规则\n".$config;
        if (@file_put_contents($config_file, $config)){
            return true;
        }else{
           return false;
        }
    }

	
}